package com.study;

import java.lang.reflect.Array;

public class SeqList<E> implements LinearList<E> {
    private int maxsize;
    private E[] data;
    private int size;

    @SuppressWarnings("unchecked")
    public SeqList(Class<E> type, int maxsize) {
        this.maxsize = maxsize;
        data = (E[]) Array.newInstance(type, maxsize);
        size = 0;
    }

    @Override
    public boolean add(E item) {
        if (!isFull()) {
            data[size++] = item;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean add(int i, E item) {
        if (i < 0 || i > size) {
            throw new IndexOutOfBoundsException("index:" + i + ",Size:" + size);
        }
        if (!isFull()) {
            for (int j = size - 1; j >= i; j--) {
                data[j + 1] = data[j];
            }
            data[i] = item;
            size++;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public E remove(int i) {
        rangeCheck(i);
        if (!isEmpty()) {
            E oldValue = data[i];
            for (int j = i; j <= size - 1; j++) {
                data[j] = data[j + 1];
            }
            data[--size] = null;
            return oldValue;
        }
        return null;
    }

    @Override
    public int indexOf(E item) {
        if (item == null) {
            for (int i = 0; i <= size - 1; i++) {
                if (data[i] == null) {
                    return i;
                }
            }
        } else {
            for (int i = 0; i <= size - 1; i++) {
                if (item.equals(data[i])) {
                    return i;
                }
            }
        }
        return -1;
    }

    @Override
    public E get(int i) {
        rangeCheck(i);
        return data[i];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++) {
            data[i] = null;
        }
        size = 0;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        if (size == maxsize) {
            return true;
        } else {
            return false;
        }
    }

    public void rangeCheck(int i) {
        if (i < 0 || i > size) {
            throw new IndexOutOfBoundsException("index: " + i + " size: " + size);
        }
    }

}
